package xmpp.androidpush.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import org.xbill.DNS.Lookup;
import org.xbill.DNS.ResolverConfig;


public abstract class PushReceiver extends BroadcastReceiver {
    private static int networkType = -1;

    public PushReceiver() {
    }

    public abstract Intent initServiceIntent(Context context);

    public static void initNetworkStatus(Context context) {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        networkType = -1;
        if (networkInfo != null && networkInfo.isConnected()) {
            networkType = networkInfo.getType();
        }
    }

    public void onReceive(Context context, Intent intent) {
        Intent xmppServiceIntent = this.initServiceIntent(context);
        if (intent.getAction().equals("android.intent.action.ACTION_SHUTDOWN")) {
            context.stopService(xmppServiceIntent);
        } else if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
            if (!this.isStartUp(context)) {
                return;
            }
            xmppServiceIntent.setAction(PushService.ACTION_START);
            context.startService(xmppServiceIntent);
        } else if (intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")) {
            if (!this.isStartUp(context)) {
                return;
            }
            ResolverConfig.refresh();
            Lookup.refreshDefault();
            ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
            boolean isConnected = networkInfo != null && networkInfo.isConnected();
            boolean wasConnected = networkType != -1;
            if (wasConnected && !isConnected) {
                networkType = -1;
                xmppServiceIntent.setAction(PushService.ACTION_DISCONNECT);
            } else if (isConnected && networkInfo.getType() != networkType) {
                networkType = networkInfo.getType();
                xmppServiceIntent.setAction(PushService.ACTION_RECONNECT);
            }

            context.startService(xmppServiceIntent);
        } else if (PushService.ACTION_CHECK_ALARM.equals(intent.getAction())) {
            if (!this.isStartUp(context)) {
                return;
            }

            xmppServiceIntent.setAction(PushService.ACTION_CHECK_ALARM);
            context.startService(xmppServiceIntent);
        }

    }

    private boolean isStartUp(Context context) {
        return PushConfig.isSatrtUp(context);
    }
}
